package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.EntDetailBean;
import com.cz.nongyetongv5.bean.JsonUtil;
import com.cz.nongyetongv5.bean.PopBean;
import com.cz.nongyetongv5.bean.SuperviseCheck;
import com.cz.nongyetongv5.bean.SuperviseList;
import com.cz.nongyetongv5.bean.SuperviseListBean;
import com.cz.nongyetongv5.bean.SuperviseListResponse;
import com.cz.nongyetongv5.custom.dialog.CustomMyDialog;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class SuperviseListNewActivity extends Activity implements View.OnClickListener {
    private RelativeLayout rl_back;
    private TextView tv_right;

    private List<PopBean> types;
    private TypeAdapter typeAdapter;
    private LinearLayout ll_type;
    private TextView tv_type;
    private LinearLayout ll_type_list;
    private RecyclerView rv_type;
    private LinearLayout ll_alpha;
    private RecyclerView rv_list;

    private LinearLayout ll_bottom;
    private TextView tv_pass;
    private TextView tv_refuse;
    private String add_user;
    private String region_code;


    private int page = 1;
    private int size = 10;
    private SuperviseListAdapter adapter;
    private List<SuperviseList> superviseLists;
    private SuperviseListResponse superviseListResponse;
    private SuperviseListBean superviseListBean;
    SmartRefreshLayout refreshLayout;
    private boolean isShowEdit = false;
    private int editType = 1;



    private String status = "1,4";
    private int currentPosition = 0;
    private List<SuperviseCheck> superviseChecks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_supervise_list_new);
        add_user = getIntent().getStringExtra("add_user");
        region_code = getIntent().getStringExtra("region_code");
        superviseChecks = new ArrayList<>();
        types = new ArrayList<>();
        types.add(new PopBean("选定的调查对象", false, "1"));
        types.add(new PopBean("注销的调查对象", false, "4"));
        types.add(new PopBean("全部调查对象", true, "1,4"));
        rl_back = findViewById(R.id.rl_back);
        ll_type_list = findViewById(R.id.ll_type_list);
        ll_alpha = findViewById(R.id.ll_alpha);
        rl_back.setOnClickListener(this);
        tv_right = findViewById(R.id.tv_right);
        tv_right.setText("审核");
        tv_right.setOnClickListener(this);
        tv_type = findViewById(R.id.tv_type);
        tv_type.setText("全部调查对象");
        rv_type = findViewById(R.id.rv_type);
        ll_bottom = findViewById(R.id.ll_bottom);
        tv_pass = findViewById(R.id.tv_pass);
        tv_refuse = findViewById(R.id.tv_refuse);
        tv_pass.setOnClickListener(this);
        tv_refuse.setOnClickListener(this);
        typeAdapter = new TypeAdapter();
        rv_type.setLayoutManager(new LinearLayoutManager(SuperviseListNewActivity.this));
        rv_type.setAdapter(typeAdapter);
        ll_alpha.setOnClickListener(this);
        typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (PopBean popupBean : types) {
                    popupBean.setChecked(false);
                }
                types.get(position).setChecked(true);
                adapter.notifyDataSetChanged();
                tv_type.setText(types.get(position).getName());
                ll_type_list.setVisibility(View.GONE);
                tv_type.setTextColor(Color.parseColor("#585858"));
                tv_type.setCompoundDrawablesWithIntrinsicBounds(0,
                        0, R.drawable.jt_down_black, 0);
                status = types.get(position).getLacationTag();
                getSuperviseList();
            }
        });
        ll_type = findViewById(R.id.ll_type);
        ll_type.setOnClickListener(this);
        rv_list = findViewById(R.id.rv_list);
        refreshLayout = findViewById(R.id.refreshLayout);
        superviseLists = new ArrayList<>();
        adapter = new SuperviseListAdapter();
        View notDataView = getLayoutInflater().inflate(R.layout.view_nodata, (ViewGroup) rv_list.getParent(), false);
        adapter.setEmptyView(notDataView);
        rv_list.setLayoutManager(new LinearLayoutManager(SuperviseListNewActivity.this));
        rv_list.setAdapter(adapter); //设置分页和下拉刷新
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setRefreshHeader(new ClassicsHeader(SuperviseListNewActivity.this));
        //设置 Footer
        refreshLayout.setRefreshFooter(new ClassicsFooter(SuperviseListNewActivity.this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getSuperviseList();
                //                WaitDialog.ShowDialog(getActivity(),"数据加载中...");

            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (superviseListBean != null) {
                    if (page < superviseListBean.getTotal()) {
                        page++;
                        getSuperviseList();
                    } else {
                        refreshLayout.finishLoadmore();
                        Toast.makeText(SuperviseListNewActivity.this, "没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    refreshLayout.finishLoadmore();
                    Toast.makeText(SuperviseListNewActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                }
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                currentPosition = position;
                getEntDetail(superviseLists.get(position).getEnt_id());
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.ll_root) {
                    currentPosition = position;
                    getEntDetail(superviseLists.get(position).getEnt_id());
                } else {
                    if (superviseLists.get(position).isChecked()) {
                        superviseLists.get(position).setChecked(false);
                    } else {
                        superviseLists.get(position).setChecked(true);
                    }
                    adapter.notifyDataSetChanged();
                    int sum = 0;
                    for (SuperviseList superviseList : superviseLists) {
                        if (superviseList.isChecked()) {
                            sum++;
                        }
                    }
                    if (sum == superviseLists.size()) {
                        tv_right.setText("全不选");
                        editType = 3;
                    } else {
                        tv_right.setText("全选");
                        editType = 2;
                    }
                }
            }
        });

        getSuperviseList();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.ll_alpha:
                if (ll_type_list.getVisibility() == View.VISIBLE) {
                    ll_type_list.setVisibility(View.GONE);
                    tv_type.setTextColor(Color.parseColor("#585858"));
                    tv_type.setCompoundDrawablesWithIntrinsicBounds(0,
                            0, R.drawable.jt_down_black, 0);
                }
                break;
            case R.id.tv_right:
                if (ll_type_list.getVisibility() == View.VISIBLE) {
                    ll_type_list.setVisibility(View.GONE);
                    tv_type.setTextColor(Color.parseColor("#585858"));
                    tv_type.setCompoundDrawablesWithIntrinsicBounds(0,
                            0, R.drawable.jt_down_black, 0);
                }
                if (superviseLists.size() == 0) {
                    Toast.makeText(SuperviseListNewActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                } else {
                    isShowEdit = true;
                    if (editType == 1) {
                        tv_right.setText("全选");
                        ll_bottom.setVisibility(View.VISIBLE);
                        editType = 2;
                        adapter.notifyDataSetChanged();
                    } else if (editType == 2) {
                        tv_right.setText("全不选");
                        ll_bottom.setVisibility(View.VISIBLE);
                        editType = 3;
                        setSelect(true);
                    } else if (editType == 3) {
                        editType = 2;
                        tv_right.setText("全选");
                        ll_bottom.setVisibility(View.VISIBLE);
                        setSelect(false);
                    }
                }
                break;
            case R.id.ll_type:
                if (ll_type_list.getVisibility() == View.GONE) {
                    ll_type_list.setVisibility(View.VISIBLE);
                    tv_type.setTextColor(Color.parseColor("#21b481"));
                    tv_type.setCompoundDrawablesWithIntrinsicBounds(0,
                            0, R.drawable.jt_up_green, 0);
                } else {
                    ll_type_list.setVisibility(View.GONE);
                    tv_type.setTextColor(Color.parseColor("#585858"));
                    tv_type.setCompoundDrawablesWithIntrinsicBounds(0,
                            0, R.drawable.jt_down_black, 0);
                }
                break;
            case R.id.tv_pass:
                superviseChecks.clear();
                if (getSelected().size() <= 0) {
                    Toast.makeText(SuperviseListNewActivity.this, "没有选择数据", Toast.LENGTH_SHORT).show();
                } else {
                    for (SuperviseList superviseList : getSelected()) {
                        superviseChecks.add(new SuperviseCheck(superviseList.getSupervise_id(), superviseList.getStatus()));
                    }

                    CustomMyDialog.Builder builder = new CustomMyDialog.Builder(SuperviseListNewActivity.this);
                    builder.setMessage("确认提交？");
                    builder.setPositiveButton("确认提交", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            postCheckSupervise("", add_user, region_code, "1", new Gson().toJson(superviseChecks));
                        }
                    });
                    builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.createNormalDialog().show();
                }
                break;
            case R.id.tv_refuse:
                superviseChecks.clear();
                if (getSelected().size() <= 0) {
                    Toast.makeText(SuperviseListNewActivity.this, "没有选择数据", Toast.LENGTH_SHORT).show();
                } else {
                    for (SuperviseList superviseList : getSelected()) {
                        superviseChecks.add(new SuperviseCheck(superviseList.getSupervise_id(), superviseList.getStatus()));
                    }
                    Intent intent2 = new Intent(SuperviseListNewActivity.this, DialogActivity.class);
                    intent2.putExtra("add_user", add_user);
                    intent2.putExtra("region_code", region_code);
                    intent2.putExtra("ids", new Gson().toJson(superviseChecks));
                    intent2.putExtra("type", "2");
                    intent2.putExtra("model", "supervise");
                    startActivityForResult(intent2, 9002);
                }
                break;
            default:
                break;
        }
    }

    public void setSelect(boolean isSelect) {
        for (SuperviseList superviseList : superviseLists) {
            superviseList.setChecked(isSelect);
        }
        adapter.notifyDataSetChanged();
    }

    public class TypeAdapter extends BaseQuickAdapter<PopBean, BaseViewHolder> {
        public TypeAdapter() {
            super(R.layout.status_pop_item, types);

        }

        @Override
        protected void convert(BaseViewHolder helper, PopBean item) {
            if (item.isChecked()) {
                helper.setTextColor(R.id.tv_name, Color.parseColor("#21b481"));
            } else {
                helper.setTextColor(R.id.tv_name, Color.parseColor("#585858"));
            }
            helper.setText(R.id.tv_name, item.getName());
        }
    }

    void getSuperviseList() {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "supervise/checkSuperviseList.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(size))
                .addParams("region_code", region_code)
                .addParams("add_user", add_user)
                .addParams("status", status)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(SuperviseListNewActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        closeRefresh();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //                        System.out.println(response);
                        closeRefresh();
                        superviseListResponse = JsonUtil.toObject(response, SuperviseListResponse.class);
                        if (superviseListResponse.getCode() == 0) {
                            superviseListBean = superviseListResponse.getData();
                            if (page == 1) {
                                superviseLists.clear();
                                superviseLists.addAll(superviseListBean.getRows());
                            } else {
                                superviseLists.addAll(superviseListBean.getRows());
                            }
                            if (superviseLists.size() == 0) {
                                editType = 1;
                                isShowEdit = false;
                                tv_right.setText("审核");
                                ll_bottom.setVisibility(View.GONE);
                                adapter.notifyDataSetChanged();
                            } else {
                                if (editType == 3) {
                                    setSelect(true);
                                } else {
                                    setSelect(false);
                                }
                            }
                        } else {
                            Toast.makeText(SuperviseListNewActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    public class SuperviseListAdapter extends BaseQuickAdapter<SuperviseList, BaseViewHolder> {
        public SuperviseListAdapter() {
            super(R.layout.supervise_list_item_new, superviseLists);
        }

        @Override
        protected void convert(BaseViewHolder helper, SuperviseList item) {
            if (item.getEnt_name() != null) {
                helper.setText(R.id.tv_ent_name, item.getEnt_name() + "（" + item.getTrade_name() + ")");
            }
            if (item.getRealname() != null) {
                helper.setText(R.id.tv_admin, item.getRealname() + "(" + item.getRegion_name() + ")");
            }
            if (item.getAdd_time() != null) {
                helper.setText(R.id.tv_date, item.getAdd_time());
            }
            if (isShowEdit) {
                helper.setVisible(R.id.cb_choose, true);
                helper.addOnClickListener(R.id.cb_choose)
                        .addOnClickListener(R.id.ll_choose);
            } else {
                helper.setVisible(R.id.cb_choose, false);
            }
            helper.addOnClickListener(R.id.ll_root);
            helper.setChecked(R.id.cb_choose, item.isChecked());

            if (item.getStatus().equals("1")) {
                helper.setText(R.id.tv_type_name, "选定");
            } else if (item.getStatus().equals("4")) {
                helper.setText(R.id.tv_type_name, "注销");
            }
        }
    }

    public void closeRefresh() {
        if (refreshLayout != null) {
            if (refreshLayout.isRefreshing()) {
                refreshLayout.finishRefresh();
            } else if (refreshLayout.isLoading()) {
                refreshLayout.finishLoadmore();
            }
        }
    }

    void getEntDetail(String id) {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "ent/entDetail.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("id", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(SuperviseListNewActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response);
                        Gson gson = new Gson();
                        EntDetailBean entDetailBean = gson.fromJson(response, EntDetailBean.class);
                        //                        EntDetailBean entDetailBean = JsonUtil.toObject(response, EntDetailBean.class);
                        if (entDetailBean.getCode() == 0) {
                            if (entDetailBean.getData() != null) {
                                Intent intent = new Intent(SuperviseListNewActivity.this, EntDetailActivity.class);
                                intent.putExtra("type", 3);
                                intent.putExtra("supervise_id", superviseLists.get(currentPosition).getSupervise_id());
                                intent.putExtra("status", superviseLists.get(currentPosition).getStatus());
                                intent.putExtra("entBean", entDetailBean.getData());
                                intent.putExtra("add_user", add_user);
                                intent.putExtra("region_code", region_code);
                                startActivityForResult(intent, 9100);
                            } else {
                                Toast.makeText(SuperviseListNewActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(SuperviseListNewActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    /**
     * 获取选中的item
     *
     * @return
     */
    public List<SuperviseList> getSelected() {
        List<SuperviseList> selectedItems = new ArrayList<>();
        for (SuperviseList superviseList : superviseLists) {
            if (superviseList.isChecked()) {
                selectedItems.add(superviseList);
            }
        }
        return selectedItems;
    }

    void postCheckSupervise(String reason, String add_user, String region_code, String type, String json) {
        OkHttpUtils
                .post()
                .url(InitApplication.newUrl + "supervise/checkSuperviseList.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("reason", "")
                .addParams("add_user", add_user)
                .addParams("region_code", region_code)
                .addParams("type", type)
                .addParams("json", json)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(SuperviseListNewActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.optInt("code");
                            if (code == 0) {
                                Toast.makeText(SuperviseListNewActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                                page = 1;
                                editType = 1;
                                isShowEdit = false;
                                tv_right.setText("审核");
                                ll_bottom.setVisibility(View.GONE);
                                getSuperviseList();
                            } else {
                                Toast.makeText(SuperviseListNewActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 9002:
                case 9100:
                    page = 1;
                    editType = 1;
                    isShowEdit = false;
                    tv_right.setText("审核");
                    ll_bottom.setVisibility(View.GONE);
                    getSuperviseList();
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
